package com.heima.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.config.ElasticSearchConfig;
import com.heima.search.service.ApArticleSearchService;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author ItZheng
 * @Date 2023/6/18 14:34
 * @Version 1.5
 */
@Service
@Slf4j
public class ApArticleSearchServiceImpl implements ApArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es:分页查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {


        //校验参数：
        if (dto == null || StringUtils.isEmpty(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取线程中userId
        Integer userId = ApThreadLocalUtils.getUser().getId();
        //校验参数：dto.getFromIndex() == 0 只有在首页时才会保存，防止多次保存
        if (userId != null && dto.getFromIndex() == 0){
            //调用保存历史查询
            apUserSearchService.insert(dto.getSearchWords(),userId);
        }

        //指定查询哪一个 索引库
        SearchRequest searchRequest = new SearchRequest("app_info_article");

        //构建Bool查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键词查询：
        MultiMatchQueryBuilder multiMatchQueryBuilder =
                QueryBuilders.multiMatchQuery(dto.getSearchWords(),"title","content");
        boolQueryBuilder.must(multiMatchQueryBuilder);
        //查询小于：
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime()));

        searchRequest.source().query(boolQueryBuilder);

        //分页：
        searchRequest.source().from(0);
        searchRequest.source().size(dto.getPageSize());

        //排序：
        searchRequest.source().sort("publishTime", SortOrder.DESC);

        //高亮：
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style ='color: red; font-size:inherit;'>");
        highlightBuilder.postTags("</font>");

        searchRequest.source().highlighter(highlightBuilder);

        SearchResponse searchResponse = null;
        //发送查询：
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }



        //3.结果封装返回

        List<Map> list = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",title);
            }else {
                //原始标题
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }

        return ResponseResult.okResult(list);
    }
}
